from docx import Document
import xlrd
import properties_util

# 删除段落
def delete_paragraph(paragraph):
    p = paragraph._element
    p.getparent().remove(p)
    p._p = p._element = None
    paragraph._p = paragraph._element = None
    # paragraph.text = ''


# 替换名称
def replace_name(paragraphs, name):
    for para in paragraphs:
        for i in range(len(para.runs)):
            name_demo = '${name}'
            if name_demo in para.runs[i].text:
                para.runs[i].text = para.runs[i].text.replace(name_demo, (str(name) + ''))
                return


# 替换留言者名称
def replace_papa_name(paragraphs, papa_name, num):
    name_demo = '${' + str(num) + '.name}'
    for para in paragraphs:
        for i in range(len(para.runs)):
            if name_demo in para.runs[i].text:
                para.runs[i].text = para.runs[i].text.replace(name_demo, papa_name+"：")
                return


# 替换文本
def replace_text(paragraphs, contents, num):
    for para in paragraphs:
        word_demo = '${' + str(num) + '.word}'
        if word_demo in para.text:
            para.text = contents + '\n'
            return


def main():
    properties = properties_util.parse("./config.properties")
    fireName = properties.get("fireName")
    print(fireName)

    # 获取sheet
    sheet = xlrd.open_workbook(r"E:\yg\xlsx\【新】YG13_杭州营___我想对你说的悄悄话_20220212202701.xls").sheets()[0]
    # 遍历整列数据

    for col in range(3, 77):
        # 打开模版文件
        document = Document(r"E:\yg\omi template1.docx")
        # 获取所有段落
        paragraphs = document.paragraphs
        # 获取姓名
        name = sheet.cell_value(rowx=0, colx=col).lstrip('.-1234567890 ')
        # 获取最大行数
        nrows = sheet.nrows
        num = 1
        # 段落数组位置
        paragraph_num = 2
        # 替换名称
        replace_name(paragraphs, name)
        for row_num in range(1, nrows):
            # 留言者姓名
            papa_name = sheet.cell_value(rowx=row_num, colx=1)
            # 留言者是否需要匿名
            if sheet.cell_value(rowx=row_num, colx=2) == '需要呀':
                papa_name = "来自一位爱你的趴趴"
            # 留言内容
            contents = sheet.cell_value(rowx=row_num, colx=col)
            # 是否删除标识
            if contents is not None and contents != '':
                print("姓名:" + name + "  留言者姓名:" + papa_name + "  留言内容:" + contents)
                replace_papa_name(paragraphs, papa_name, num)
                replace_text(paragraphs, contents, num)
                num += 1
                paragraph_num += 2

        # 替换完，删除多余段落，保存
        for i in range(paragraph_num, len(paragraphs)):
            delete_paragraph(paragraphs[i])
        document.save('E:/yg/生成/杭州/yg13杭州/' + name + '.docx')

if __name__ == '__main__':
    main()